﻿using Activity.Consts;
using Activity.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Activity.Helper
{
   public class OAuthHelper
    {
        /// <summary>
        /// 完整授权
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static ErrorMessage Authenticate(string code)
        {
            var url = string.Format(WeiXinConst.WeiXin_User_OpenIdUrl, code);
            var result = HttpClientHelper.GetResponse<Oauth2AccessToken>(url);
            Log.WriteLog(result.ErrCode.ToString() + result.ErrMsg);
            if (result.ErrCode != 0)
            {
                return result;
            }
            //RefreshTokenUrl
            url = string.Format(WeiXinConst.RefreshTokenUrl, result.refresh_token);
            result = HttpClientHelper.GetResponse<Oauth2AccessToken>(url);
            Log.WriteLog(result.ErrCode.ToString() + result.ErrMsg);
            if (result.ErrCode != 0) return result;
            url = string.Format(WeiXinConst.Weixin_User_Userinfo, result.access_token, result.openid);
            var userInfo = HttpClientHelper.GetResponse<WeiXinUserInfo>(url);
            return userInfo;
        }
        /// <summary>
        /// 静默授权，只能得到OpenID
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Oauth2AccessToken SilenceAuthenticate(string code)
        {
            var url = string.Format(WeiXinConst.WeiXin_User_OpenIdUrl, code);
            var result = HttpClientHelper.GetResponse<Oauth2AccessToken>(url);
            return result;
        }
        public class Oauth2AccessToken : ErrorMessage
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public string refresh_token { get; set; }
            public string openid { get; set; }
            public string scope { get; set; }
            public string unionid { get; set; }
        }
    }
}
